<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="40%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './user.data';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {getUserDetails, updateUser} from './user.api';

// 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const rowId = ref('');
  const deptOptions = ref([]);

  const wrapperCol: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 24, // ≥992px
    xl: 24, // ≥1200px
    xxl: 24, // ≥1600px
  }
  //表单配置
  const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 80,
    baseColProps: { lg: 24, md: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol
  });
  

  //表单赋值
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setDrawerProps({ loading: true })
      try {
        rowId.value = data.record.id;
        //租户信息定义成数组
        if (data.record.tenantIds && !Array.isArray(data.record.tenantIds)) {
          data.record.tenantIds = data.record.tenantIds.split(",");
        }
        //查角色/赋值/try catch 处理，不然编辑有问题
        try {
          data.record = await getUserDetails({userId: data.record.id});
          const userRoles = data.record.roleList;
          if(userRoles && userRoles.length > 0 ){
              data.record.roleIds = userRoles.map(e => e.id)
          }

          // 查所属部门/赋值
          const userDept = data.record.deptList;
          if(userDept && userDept.length > 0 ){
              let selectDeptKeys = Array.from(userDept, ({key}) => key);
              data.record.deptIds = selectDeptKeys.join(",");
              deptOptions.value = userDept.map(item=>{
                return {label: item.title, value: item.key}
              });
          }
        } catch (error) {
        }

      } finally {
        setDrawerProps({ loading: false })
      }
    }
    setFieldsValue({ ...data.record })

    //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
    updateSchema([
      {
        field: 'password',
        show: !unref(isUpdate),
      },
      {
        field: 'confirmPassword',
        ifShow: !unref(isUpdate),
      },
      {
        field: 'roleIds',
        show: !data.isRole
      },
      {
        field: 'deptIds',
        componentProps:({formActionType, formModel}) => {
          return {
            sync: false,
            checkStrictly: true,
            defaultExpandLevel: 3,
            options: deptOptions.value,
            // 不允许搜索
            showSearch: false,
            onSelect: (options, values) => {
              const {updateSchema} = formActionType;
              console.log("values: ", values);
            }
          }
        }
      },
      {
        field: 'selectedDepts',
        show: !data?.departDisabled ?? false
      }
    ]);
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter })
  });
  //获取标题
  const getTitle = computed(() => '编辑用户');

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});
      values.userIdentity === 1 && (values.deptIds='');
      //提交表单
      await updateUser(values);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success', {values: {...values, id: rowId.value}});
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
